window.chatsocket = {
	timedTask: null, // 心跳包定时任务
	openTimedTask: null, // 重新连接定时任务
	socket: null,
	// 是否已连接
	connected: function() {
		return chatsocket.socket != null &&
			chatsocket.socket != undefined &&
			chatsocket.socket.readyState == WebSocket.OPEN;
	},
	open: function() {
		if (window.WebSocket) {
			// 如果当前的状态已经连接，那就不需要重复初始化websocket
			if (chatsocket.connected()) {
				return false;
			}
			// 创建websocket连接
			console.log(app.formatDate(new Date()) + ': [info]' + ' ======> [websocket开始建立连接...]: ' + app.chatServerUrl);
			chatsocket.socket = new WebSocket(app.chatServerUrl);
			chatsocket.socket.onconnection = chatsocket.wsconnection;
			chatsocket.socket.onopen = chatsocket.wsopen;
			chatsocket.socket.onclose = chatsocket.wsclose;
			chatsocket.socket.onerror = chatsocket.wserror;
			chatsocket.socket.onmessage = chatsocket.wsmessage;
		} else {
			alert("手机设备过旧，请升级手机设备...");
		}
	},
	// 发送信息
	sendMessage: function(data, count, call) {
		if (!chatsocket.connected()) {
			chatsocket.open(); // websocket建立连接
			setTimeout(() => {
				if (count > 5) {
					console.log(app.formatDate(new Date()) + ': [error]' + ' ======> [websocket发送消息失败]：' + data);
					app.showToast('发送消息失败', "error");
					return;
				}
				if (count == null) {
					count = 1;
				} else {
					count++;
				}
				chatsocket.sendMessage(data, count);
			}, 1000);
		} else { // 如果当前websocket的状态是已连接，则直接发送
			console.log(app.formatDate(new Date()) + ': [info]' + ' ======> [websocket发送消息][count=' + count + ']：' + data);
			chatsocket.socket.send(data);
			if(typeof call === 'function'){
				call();
			}
		}
	},
	wsconnection: function(ws,req) {
		console.log(JSON.stringify(ws));
		console.log(JSON.stringify(req));
	},
	wsopen: function() {
		console.log(app.formatDate(new Date()) + ': [info]' + ' ======> [websocket建立连接完成]: ' + app.chatServerUrl);
		// 构建messageData
		let md = messageData.create(messageData.type.CONNECT, null, null);
		// 发送消息
		chatsocket.sendMessage(JSON.stringify(md), null, () => {
			// 定时发送心跳
			if (!chatsocket.timedTask) {
				chatsocket.timedTask = setInterval(chatsocket.keepalive, 10000);
			}
		});
	},
	wsmessage: function(res) {
		console.log(app.formatDate(new Date()) + ': [info]' + ' ======> [接收到新消息]: ' + res.data);
		let user = app.getCacheUser();
		let chatWebview = plus.webview.getWebviewById("chat.html");
		// 转换DataContent为对象
		let dataContent = JSON.parse(res.data);
		let messageType = dataContent.header.messageType;
		// 好友申请
		if (messageType == messageData.type.PULL_FRIEND) {
			// 获取好友申请
			chatWebview.evalJS('requestFriendRequests()');
			return false;
		}
		// 获取接收到的消息
		let extension = dataContent.extension;
		let chatMessage = extension.chatMessage;
		if(!chatMessage){
			return;
		}
		let sendUserId = chatMessage.sendUserId;
		let userId = app.getUserId();
		let msg = {
			messageId: chatMessage.id,
			createTime: chatMessage.createTime,
			message: chatMessage.message,
			status: 0,
			receiveUserId: chatMessage.receiveUserId,
			sendUserId: chatMessage.sendUserId,
			type: 1,
			isMyself: chatMessage.sendUserId == userId ? 1 : 0
		}

		// 调用聊天webview的receiveMsg方法
		var chatingWebview = plus.webview.getWebviewById("chatting-" + sendUserId);
		var isRead = true; // 设置消息的默认状态为已读
		if (chatingWebview != null) {
			// 保存聊天历史记录到本地数据库
			chatmessagedb.insert(msg, () => {
				// 保存聊天快照记录到本地缓存
				let friendId = sendUserId;
				let status = 0;
				chatmessagedb.selectCount({userId, friendId, status}, (data3) => {
					msg.unread = 0;
					chatsnapshotmessagedb.insert(msg, () => {
						chatingWebview.evalJS("receiveMsg('" + msg.message + "')");
						chatingWebview.evalJS("resizeScreen()");
						// 接受到消息之后，对消息记录进行签收
						chatsocket.signMsgList([msg.messageId], userId);
						// 加载聊天快照列表
						if (chatWebview != null) {
							chatWebview.evalJS("loadingChatSnapshot()");
						}
					});
				})
			});
		} else {
			// 保存聊天历史记录到本地数据库
			chatmessagedb.insert(msg, () => {
				// 保存聊天快照记录到本地缓存
				let friendId = sendUserId;
				let status = 0;
				chatmessagedb.selectCount({userId, friendId, status}, (data3) => {
					msg.unread = data3 == null ? 0 : data3[0].count;
					chatsnapshotmessagedb.insert(msg, () => {
						// 接受到消息之后，对消息记录进行签收
						chatsocket.signMsgList([msg.messageId], userId);
						// 加载聊天快照列表
						if (chatWebview != null) {
							chatWebview.evalJS("loadingChatSnapshot()");
						}
					});
				})
			});
		}
		
	},
	wsclose: function() {
		console.log(app.formatDate(new Date()) + ': [error]' + ' ======> [websocket连接已关闭]: ' + app.chatServerUrl);
		// if(chatsocket.timedTask){
		// 	clearInterval(chatsocket.timedTask);// 关闭定时心跳包发送
		// }
	},
	close: () => {
		console.log(app.formatDate(new Date()) + ': [error]' + ' ======> [主动关闭websocket]: ' + app.chatServerUrl);
		if(chatsocket.socket && chatsocket.connected()){
			chatsocket.socket.close();
		}
	},
	wserror: function(e) {
		console.log(app.formatDate(new Date()) + ': [error]' + ' ======> [websocket连接发生错误]: ' + app.chatServerUrl + ': ' + JSON.stringify(e));
		let count = 1;
		if(!chatsocket.openTimedTask){ // 如果还未开启定时任务
			chatsocket.openTimedTask = setInterval(() => {
				if(count++ > 5){
					clearInterval(chatsocket.openTimedTask);// 关闭重新连接定时任务
				} else{
					chatsocket.open();
				}
			}, 2000);
		}
	},
	keepalive: function() {
		// 构建messageData
		let md = messageData.create(messageData.type.KEEPALIVE, null, null);
		// 发送心跳
		chatsocket.sendMessage(JSON.stringify(md));
	},
	signMsgList: function(msgIds, userId) {
		if (!msgIds) {
			return;
		}
		// 构建批量签收对象的模型
		var msg = {
			header: {
				messageType: messageData.type.SIGNED,
				signUserId: userId
			},
			extension: {
				messageIdArr: msgIds
			}
		};
		// 发送批量签收的请求
		chatsocket.sendMessage(JSON.stringify(msg));
	},
}
